package hu.veilingsite.shared;

import java.util.Date;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;

public class FieldVerifier {

	public static boolean isValidName(String name) {
		if (name == null) {
			return false;
		}
		return name.length() > 3;
	}
	
	public static boolean isValidEmailadres(String email) {
		email = escapeHtml(email);
		if (email == null || !email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.(?:[a-zA-Z]{2,6})$")) {
			return false;
		}
		return true;
	}

	public static boolean isValidWachtwoord(String ww) {
		ww = escapeHtml(ww);
		if (ww == null || ww.length() < 4) {
			return false;
		}
		return true;
	}

	public static String fromDateToString(Date datum) {
		try {
			return DateTimeFormat.getFormat("d-M-y").format(datum);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Converteren van Datum naar String mislukt.");
		}
	}

	public static Date fromStringToDate(String s) {
		try {
			return DateTimeFormat.getFormat("d-M-y").parse(s);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Converteren naar datum mislukt.");
		}
	}

	private static String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}
	
	public static DialogBox showMessageBox(String titel, String html, boolean anime) {
		final DialogBox box = new DialogBox();
		final Button closeButton = new Button("Ok");
		
		box.setText(titel);
		box.setAnimationEnabled(anime);
		box.center();

		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.add(new HTML (html));
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		box.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				box.hide();
			}
		});
		return box;
	}
	public static java.sql.Date convertUtilDateToSqlDate(java.util.Date uD) {
		java.util.Date utilDate = new java.util.Date(); 
	    return new java.sql.Date(utilDate.getTime()); 

		/* Calendar cal = Calendar.getInstance();
		java.util.Date utilDate = uD;
		cal.setTime(utilDate);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return new java.sql.Date(cal.getTime().getTime());*/
	}
}
